<template>
  <div>
    <div v-drag id="modleView" class="layer-control" :style="styles" ref="layerControl">
      <div class="pre" @click="loadPreLayers" v-if="showPre"></div>
      <ul class="layer" ref="layerHeight">
        <template v-for="(item,index) in showLayers">
          <li :key="index" class="layer-detail" v-if="item && item.show">
            <!-- <div class="layer-title" :style="{background:background}">
              {{item.name}}
              <span class="layer-btn" @click="removeLayer(item)">
                <i class="iconfont icon-yanjing"></i>
              </span>
            </div>-->

            <div @click.stop.capture="setOverLayerColor($event,index)">
              <div class="layer-content" v-html="item.html"></div>
            </div>
          </li>
        </template>
        <li class="layer-title">图例</li>
      </ul>
      <div class="more" @click="loadMoreLayers" v-if="showMore"></div>
        <color-picker
          v-if="ColorPickerVisible"
          :left="leftColorPicker"
          :bottom="bottomColorPicker"
          :curClickLayer="curClickLayer"
          @close="ColorPickerVisible = false"
          @colors="setCustomOverLayerColor"
        ></color-picker>
    </div>
  </div>
</template>

<script>
import { setTimeout } from "timers";
import sgisLayerBase from "@/utils/map/sfgis.layer.base.js";
import sgisMapBase from "@/utils/map/sfgis.map.base.js";
import ColorPicker from "@/components/colorPicker/index";

export default {
  name: "LegendFrame",
  props: ["top", "left", "bottom", "right", "background", "otherLegend"],
  components: { ColorPicker },
  data() {
    return {
      styles: {
        position: "absolute",
        bottom: "183px",
        left: "256px",
        cursor: "move"
      },
      showLayers: [],
      curPosition: {
        start: 0,
        len: 0
      },
      showPre: false,
      showMore: false,
      layers: sgisLayerBase.overLayers,
      leftColorPicker: "340px",
      bottomColorPicker: "0px",
      curClickLayer: -1, // 当前点击图层显示颜色选择器
      ColorPickerVisible: false
    };
  },
  created() {
    this.layers = this.otherLegend
      ? this.otherLegend
      : sgisLayerBase.overLayers;
    this.initPosition();

    this.showLayers = this.layers.slice(0);
  },
  mounted() {
    if (this.layers.length) {
      this.calLayerControlStyle();
    } else {
      this.showLayers = this.layers.slice(0);
    }
    // const cal = () => {
    //   setTimeout(() => {
    //     // reset params
    //     this.showPre = false;
    //     this.showMore = false;
    //     this.curPosition = {
    //       start: 0,
    //       len: 0
    //     };
    //     this.showLayers = this.layers.slice(0);
    //     // reset params
    //     this.$nextTick(() => {
    //       try {
    //         this.calLayerControlStyle();
    //       } catch (err) {
    //         console.log(err);
    //       }
    //     });
    //   }, 1000);
    // };
    // $(window).resize(cal);
  },
  //自定义指令（移动div）
  directives: {
    drag(el, bindings) {
      var x = 0;
      var y = 0;
      var l = 0;
      var t = 0;
      var isDown = false;
      //鼠标按下事件
      el.onmousedown = function(e) {
        //获取x坐标和y坐标
        x = e.clientX;
        y = e.clientY;

        //获取左部和顶部的偏移量
        l = el.offsetLeft;
        t = el.offsetTop;
        //开关打开
        isDown = true;
        //设置样式
        el.style.cursor = "move";
      };
      //鼠标移动
      window.onmousemove = function(e) {
        if (isDown == false) {
          return;
        }
        //获取x和y
        var nx = e.clientX;
        var ny = e.clientY;
        //计算移动后的左偏移量和顶部的偏移量
        var nl = nx - (x - l);
        var nt = ny - (y - t);

        el.style.left = nl + "px";
        el.style.top = nt + "px";
      };
      //鼠标抬起事件
      el.onmouseup = function() {
        //开关关闭
        isDown = false;
        el.style.cursor = "default";
      };
    }
  },
  methods: {
    setCustomOverLayerColor(color) {
      let that = this;
      const colors = color.slice(0);
      for (const key in colors) {
        colors[key] = "#" + colors[key];
      }
      const layerInfo = this.showLayers[this.curClickLayer];
      sgisMapBase.map.overlayers[layerInfo.layerId].setCustomColor(sgisMapBase.map.overlayers[layerInfo.layerId], {
        colors
      });
   
     let overLayers = sgisLayerBase.overLayers;
      overLayers.map((item)=>{
        that.showLayers.map((layer,index)=>{
          if(item.layerId == layer.layerId){
            that.showLayers[index] = item;
          }
        });
      })
      that.showLayers= JSON.parse(JSON.stringify(that.showLayers));
    },
    setOverLayerColor(e, index) {
      this.curClickLayer = index;
      // this.leftColorPicker = e.clientX - e.offsetX + 140 + "px";
      this.leftColorPicker = "334px";
      this.bottomColorPicker = "2px";
      const layerInfo = this.showLayers[this.curClickLayer];
      const layer = sgisMapBase.map.overlayers[layerInfo.layerId];
      if (layer.hasOwnProperty("setCustomColor")) {
        this.ColorPickerVisible = true;
      }
    },
    removeLayer(item) {
      this.ColorPickerVisible = false;
      if (this.otherLegend) {
        this.$emit("closeLegend", item);
        return;
      }
      sgisLayerBase.removeOverLayer(item.layerId);
    },
    initPosition() {
      if (this.top) {
        // this.styles.top = this.top;
      }
      if (this.left) {
        this.styles.left = this.left;
      }
      if (this.bottom) {
        this.styles.bottom = this.bottom;
      }
      if (this.top) {
        this.styles.right = this.right;
      }
    },
    calLayerControlStyle() {
      const oB = this.$refs["layerControl"];
      const style = this.computeElStyle(oB, null);
      const elHeight = parseInt(style.height.slice(0, -2));
      const elWidth = parseInt(style.width.slice(0, -2)) - 90;
      // if (elHeight) {
      //   this.reCalLayerControlStyle(oB, elHeight, elWidth);
      // }
    },
    reCalLayerControlStyle(oB, elHeight, elWidth) {
      // 超出篇幅计算开始
      const layersEl = oB.querySelectorAll("li");
      let layerWidth = 0;
      this.showLayers = [];
      let key = this.curPosition.start;
      if (key < 0) {
        key = 0;
      }
      let count = 0;
      for (key; key < layersEl.length; key++) {
        count++;
        const item = layersEl[key];
        const layerStyle = this.computeElStyle(item);
        layerWidth += parseInt(layerStyle.width.slice(0, -2)) + 10;
        if (layerWidth > elWidth) {
          return;
        }
        if (count > 4) {
          return;
        }
        this.showLayers.push(this.layers[key]);
        this.curPosition = {
          ...this.curPosition,
          len: this.showLayers.length
        };
        if (
          this.curPosition.start + this.showLayers.length <
          this.layers.length
        ) {
          this.showMore = true;
        } else {
          this.showMore = false;
        }
        if (this.curPosition.start !== 0) {
          this.showPre = true;
        } else {
          this.showPre = false;
        }
      }
      // 超出篇幅计算结束
    },
    loadPreLayers() {
      this.showLayers = this.layers.slice(0);
      this.showMore = true;
      this.$nextTick(() => {
        const oB = this.$refs["layerControl"];
        const style = this.computeElStyle(oB, null);
        const elHeight = parseInt(style.height.slice(0, -2));
        const elWidth = parseInt(style.width.slice(0, -2));
        if (elHeight) {
          this.reCalLayerStyleP(oB, elHeight, elWidth);
        }
      });
    },
    loadMoreLayers() {
      this.showLayers = this.layers.slice(0);
      this.showPre = true;
      this.$nextTick(() => {
        const oB = this.$refs["layerControl"];
        const style = this.computeElStyle(oB, null);
        const elHeight = parseInt(style.height.slice(0, -2));
        const elWidth = parseInt(style.width.slice(0, -2));
        if (elHeight) {
          this.reCalLayerStyle(oB, elHeight, elWidth);
        }
      });
    },
    reCalLayerStyle(oB, elHeight, elWidth) {
      // 超出篇幅计算开始
      const layersEl = oB.querySelectorAll("li");
      let layerWidth = 0;
      this.showLayers = [];
      let key = this.curPosition.start + this.curPosition.len;
      this.curPosition.start = key;
      let count = 0;
      for (key; key < layersEl.length; key++) {
        count++;
        const item = layersEl[key];
        const layerStyle = this.computeElStyle(item);
        layerWidth += parseInt(layerStyle.width.slice(0, -2)) + 10;
        if (layerWidth > elWidth) {
          return;
        }
        if (count > 4) {
          return;
        }
        this.showLayers.push(this.layers[key]);
        this.curPosition = {
          ...this.curPosition,
          len: this.showLayers.length
        };
        const isA = this.curPosition.start + this.curPosition.len;
        if (isA >= this.layers.length) {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
      }
      // 超出篇幅计算结束
    }, // 计算往后翻页
    reCalLayerStyleP(oB, elHeight, elWidth) {
      // 超出篇幅计算开始
      const layersEl = oB.querySelectorAll("li");
      let layerWidth = 0;
      this.showLayers = [];
      let key = this.curPosition.start - 1;
      let count = 0;
      for (key; key >= 0; key--) {
        count++;
        const item = layersEl[key];
        const layerStyle = this.computeElStyle(item);
        layerWidth += parseInt(layerStyle.width.slice(0, -2)) + 10;
        if (layerWidth > elWidth) {
          return;
        }
        if (count > 4) {
          return;
        }
        this.showLayers.unshift(this.layers[key]);
        this.curPosition = {
          start: key,
          len: this.showLayers.length
        };
        if (key === 0) {
          this.showPre = false;
        }
      }
      // 超出篇幅计算结束
    }, // 计算往前翻页
    computeElStyle(el) {
      let style = "";
      try {
        style = document.defaultView.getComputedStyle(el, null);
      } catch (err) {
        console.log(err);
      }
      return style;
    }
  },
  watch: {
    layers() {
      // reset params
      this.showPre = false;
      this.showMore = false;
      this.showLayers = this.layers.slice(0);
      // 特殊情况
      if (!this.layers.length) {
        this.curPosition = {
          start: 4,
          len: 4
        };
        return;
      }
      // this.styles.bottom = 24 + 30*(this.layers.length - 1) + 20 +"px"
      // 特殊情况
      if (this.curPosition.start >= this.showLayers.length) {
        this.curPosition.start -= 4;
      }

      // reset params
      this.$nextTick(() => {
        try {
          this.calLayerControlStyle();
        } catch (err) {}
      });
    },
    otherLegend() {
      this.layers = this.otherLegend
        ? this.otherLegend
        : sgisLayerBase.overLayers;
    }
  }
};
</script>

<style rel='stylesheet' lang='scss' scoped>
@import "./../../styles/rule.scss";
.layer{
  position: absolute;
  bottom: 0;
}
.layer-control {
  position: absolute;
  display: flex;
  align-items: flex-end;
  justify-content: flex-start;
  left: 330px;
  // height: 300px;
  bottom: 15px;
  display: flex;
  align-items:flex-end;
  display: flex;
  align-items: center;
  z-index: 1200;
  height: 100px;
  // bottom: 20px!important;
  ul.layer {
    margin: 0;
    background: rgba(18,90,120,0.5);
    margin:0 60px;
    padding-top:10px;
    // display: table-cell;
    display: flex;
    flex-direction:column-reverse;
    .layer-title{
      list-style: none;
      text-align: center;
      color:$fontColorW;
      padding:4px 0 ;
    }
    .layer-detail {
      color: $fontColor;
      position: relative;
      list-style: none;
      display: inline-block;
      vertical-align: bottom;
      // box-sizing: border-box;
      border-radius: 5px;
      bottom: 0;
      .layer-title {
        line-height: 35px;
        // color: $fontColorW;
        font-weight: bold;
        font-size: $fontSizeNav;
        padding-left: 10px;
        // background: $colorBackground;
        background: $backGroundColorDeep;
        border-radius: 5px 5px 0 0;
        .layer-btn {
          cursor: pointer;
        }
      }
      .layer-content {
        // background: rgba(255, 255, 255, 0.5);
        // width: 140px;
        // overflow-x: hidden;
        // overflow-y: auto;
        border-radius: 0 0 5px 5px;
        cursor: pointer;
      }
    }

  }
  .more {
    width: 20px;
    height: 20px;
    transform: rotate(-90deg);
    text-align: center;
    border-radius: 50%;
    font-size: $fontSizeTitle;
    color: $fontColorW;
    background: url('../../../static/images/next.png') no-repeat;
    background-size: 100%;
    opacity: 1;
    position: absolute;
    right: 10px;
    // top: 45%;
    z-index: 999;
    cursor: pointer;
  }
  .more:hover {
    transform: scale(1.1, 1.1);
    transform: rotate(-90deg);
    opacity: 1;
  }
  .pre {
    width: 20px;
    height: 20px;
    transform: rotate(90deg);
    line-height: 35px;
    text-align: center;
    border-radius: 50%;
    font-size: $fontSizeTitle;
    color: $fontColorW;
     background: url('../../../static/images/next.png') no-repeat;
     background-size: 100%;
    opacity: 1;
    position: absolute;
    left: 10px;
    // top: 45%;
    z-index: 999;
    cursor: pointer;
  }
  .pre:hover {
    transform: scale(1.1, 1.1);
        transform: rotate(90deg);
    opacity: 1;
  }
}
</style>
<style rel='stylesheet' lang="scss">
  @import "./../../styles/rule.scss";
  .layer-control {
    .chart_item{
      display: inline-block;
      padding: 5px;
    }
    .chart_item div{
       float: left;
    }
    .chart_item img{
       float: left;
    }
    .chart_item p{
      color:$fontColorW;
      float: left;
      line-height: 3;
      margin-left: 10px;
      z-index: 1200;
    }
  }
</style>
